package com.TinyBBS.servlet;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.TinyBBS.bean.User;
import com.TinyBBS.db.Config;
import com.TinyBBS.model.UserModel;
import com.TinyBBS.util.Util;

/**
 * Servlet implementation class Login
 */
public class Login extends HttpServlet {
	private static final long serialVersionUID = 1L;

	@Override
	protected void service(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String uri = "";
		String error = "";
		HttpSession session = request.getSession(true);
		String username = (String) session.getAttribute("username");
		if(username != null){
			uri = "Profile";
		}else{
		if (request.getParameter("loginsubmit") == null) {
			uri = "views/login.jsp";
		} else {
			String password = request.getParameter("password").trim();
			String email = request.getParameter("email").trim();
			User user = new User();
			UserModel userM = new UserModel();
			user = userM.verifyUser(email,Util.getHashWithSalt(password, Config.SALT));
			if (user != null) {
				if(user.getAccess_level() != Config.PENDING){
				session.setAttribute("username", user.getUsername());
				session.setAttribute("id", user.getId());
				session.setAttribute("access_level", user.getAccess_level());
				uri = "Profile";
				}else{
					error = "Your account is not activated";
					uri = "views/login.jsp";
				}
			}else {
				error = "Your password/email is/are incorrect";
				uri = "views/login.jsp";
			}
		}
		}
		request.setAttribute("error", error);
		System.out.println();
		RequestDispatcher rd = request.getRequestDispatcher(uri);
		rd.forward(request, response);
	}
	

}
